from flask import Blueprint, request, jsonify, g
from schemas import QASchema
from .forms  import QuestionForm
from models.qa import QAModel
from extension import db
from decorators import login_required
bp = Blueprint('qa', __name__, url_prefix='/qa')

@bp.route('/questions', methods=['GET'])
def index():
    questions = QAModel.query.order_by(QAModel.create_time.desc()).all()
    question_schema = QASchema(many=True)

    return jsonify({
       'status':'success',
        'code': 200,
        'data': question_schema.dump(questions)
    })

@bp.route('/question/<int:id>', methods=['GET'])
def detail(id):
    question = db.session.query(QAModel).get(id)
    if not question:
        return jsonify({
           'status': 'fail',
            'code': 400,
            'message': '不存在',
        })
    return jsonify({
        'status': 'success',
        'code': 200,
        'data': {
            "title": question.title,
            "content": question.content,
            "author": question.author.username,
            "create_time": question.create_time.strftime('%Y-%m-%d %H:%M:%S')
        }
    })

@bp.route('/public', methods=['POST'])
@login_required
def qa_public():
    form = QuestionForm(request.form)
    if form.validate():
        title = form.title.data
        content = form.content.data
        print('user:', g.user)
        question = QAModel(title=title, content=content, author=g.user)
        db.session.add(question)
        db.session.commit()
        return jsonify({
           'status': 'success',
            'code': 200,
            'message': '问题发布成功',
        })
    else:
        return jsonify({
            'status': 'fail',
            "code": 400,
            "message": form.errors
        })

@bp.route('/search', methods=['POST'])
def qa_search():
    q = request.args.get('q')
    questions = QAModel.query.filter(QAModel.title.like('%' + q + '%')).all()
    question_schema = QASchema(many=True)
    return jsonify({
        'status': 'success',
        'code': 200,
        'data': question_schema.dump(questions)
    })
